package com.example.fp.cgc.websocket

import com.example.fp.cgc.connerlt.AlarmTask
import com.example.fp.cgc.controller.MessageController.Companion.messageController
import com.example.fp.cgc.entity.Message
import com.example.fp.cgc.mapper.MessageMapper
import com.google.gson.Gson
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Component
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import javax.websocket.*
import javax.websocket.server.PathParam
import javax.websocket.server.ServerEndpoint
import kotlin.collections.HashMap


@ServerEndpoint("/chat/{idData}")
@Component
open class ChatServer {


    var log = LoggerFactory.getLogger(WebSocketServer::class.java)

    companion object {
        private val onlineUserMap = HashMap<Int, MutableMap<Int, ChatServer>>()

        @get:Synchronized
        var chatCount = 0

        @Synchronized
        fun addChatCount() {
            chatCount++
        }
    }

    private var session: Session? = null
    @OnOpen
    open fun onOpen(
            @PathParam("idData") idData: String,
            session: Session) {
        val id = idData.split("&")
        val uid = id[0].toInt()
        val oid = id[1].toInt()
        this.session = session
        addChatCount()

        onlineUserMap.getOrPut(uid) { hashMapOf() }[oid] = this

        log.info("有新聊天面板创建,当前面板数为${chatCount}")

        this.sendMessage(getUnread(uid, oid))
        messageController.messageMapper.setRead(uid, oid)
        /**
         * 创建聊天面板时 更新主页消息阅读状态
         */
        AlarmTask.task.sendMessageData(uid,true)
        /**
         * 创建聊天面板时 更新主页历史状态
         */
        AlarmTask.task.sendMessageData(uid,false)
    }

    @OnError
    open fun onError(session: Session, error: Throwable) {
        log.error("接口访问错误")
        println(error.fillInStackTrace())
    }

    @OnClose
    open fun onClose(
            @PathParam("idData") idData: String,
            session: Session) {
        chatCount--
        val id = idData.split("&")
        val uid = id[0]
        val oid = id[1]
        onlineUserMap[uid.toInt()]?.remove(oid.toInt())
        log.info("有一位用户关闭聊天面板,当前聊天面板数为${chatCount}")
    }

    @OnMessage
    @Throws(IOException::class)
    open fun onMessage(message: String, session: Session) {
        //session.basicRemote.sendText(message)
        println("message:$message")
        val message1 = Gson().fromJson(message, Message::class.javaObjectType)
        println(message1)
        singleSend(message1)
    }

    @Throws(IOException::class)
    open fun sendMessage(message: String) {
        session?.basicRemote?.sendText(message)
    }

    /**
     * @since 2020-02-14
     * @author 蔡
     * 对特定用户发送消息
     */
    @Throws(IOException::class)
    open fun singleSend(message: Message) {
        val toId = message.toId
        val uid = message.fromId

        val date = Date() //获得系统时间.

        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val nowTime = sdf.format(date)
        val time = sdf.parse(nowTime)

        message.messageDate = time

        if (onlineUserMap[toId]?.containsKey(uid) == true) {
            message.isRead = true
            onlineUserMap[toId]?.get(uid)?.sendMessage(getMessage(message))
            messageController.messageMapper.insert(message)

        }else{
            message.isRead = false
            messageController.messageMapper.insert(message)

            AlarmTask.task.sendMessageData(toId,true)
        }
        println("发送给自己")
        AlarmTask.task.sendMessageData(uid,false)
        println("发送给对方")
        AlarmTask.task.sendMessageData(toId,false)
        AlarmTask.task.sendMessageBox(toId)
    }

    /**
     * @since 2020-02-18
     * @author 蔡
     * 获得消息
     */
    open fun getMessage(message: Message): String {
        return """
            {"type": [{
                "type" : "message"
              }],
              "message":[
                  ${Gson().toJson(message)}
              ]}
        """.trimIndent()
    }

    /**
     * @since 2020-02-18
     * @author 蔡
     * 获得未读消息
     */
    open fun getUnread(uid: Int, oid: Int): String {
        val message = messageController.messageMapper.getNewMessage(uid, oid)
        var da = """
            {"type": [{
                "type" : "Unread"
              }],
              "message":[
                  
        """.trimIndent()

        message.forEach { m ->
            da += Gson().toJson(m)
            da += ","
        }

        da = da.substring(0, da.length - 1)

        da += """ 
                ]}
        """.trimIndent()
        return da
    }
}